<template>
  <div class="video-upload-page">
    <h2 class="page-title">视频上传与管理</h2>

    <!-- 左右布局容器 -->
    <div class="layout-container">
      <!-- 左侧上传区域 -->
      <div class="upload-container">
        <el-card>
          <div slot="header">视频上传</div>

          <!-- 上传组件 -->
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :file-list="fileList"
            :before-upload="handleBeforeUpload"
            :on-progress="handleProgress"
            :on-success="handleSuccess"
            :on-error="handleError"
            :auto-upload="false"
            accept="video/mp4,video/avi,video/mov,video/flv"
          >
            <!-- 上传按钮 -->
            <el-button type="primary">选择视频文件</el-button>
            <div slot="tip" class="upload-tip">
              支持格式：MP4、AVI、MOV、FLV<br>
              单个文件大小不超过 200MB
            </div>
          </el-upload>

          <!-- 上传控制 -->
          <div class="upload-controls" v-if="fileList.length > 0">
            <el-progress
              :percentage="uploadProgress"
              stroke-width="6"
              v-if="uploading"
            ></el-progress>
            <div class="btn-group">
              <el-button
                @click="submitUpload"
                type="success"
                :disabled="uploading || fileList.length === 0"
              >
                <i class="el-icon-upload" v-if="!uploading"></i>
                <i class="el-icon-loading" v-if="uploading"></i>
                {{ uploading ? '上传中...' : '开始上传' }}
              </el-button>
              <el-button
                @click="clearFiles"
                type="warning"
                :disabled="uploading"
              >
                清空
              </el-button>
            </div>
          </div>

          <!-- 上传状态提示 -->
          <el-alert
            :title="statusMessage"
            :type="statusType"
            v-if="showStatusAlert"
            closable
            @close="showStatusAlert = false"
          ></el-alert>
        </el-card>
      </div>

      <!-- 右侧预览与列表区域 -->
      <div class="preview-container">
        <el-card>
          <div slot="header">视频预览</div>

          <!-- 预览区 -->
          <div class="preview-box" v-if="previewVideoUrl">
            <video
              :src="previewVideoUrl"
              controls
              class="preview-video"
              :poster="videoPoster"
            >
              您的浏览器不支持视频播放
            </video>
            <div class="video-info">
              <p><strong>文件名：</strong>{{ currentVideoName }}</p>
              <p><strong>大小：</strong>{{ formatSize(currentVideoSize) }}</p>
              <p><strong>时长：</strong>{{ currentVideoDuration }}</p>
            </div>
          </div>

          <!-- 无预览时显示 -->
          <div class="empty-preview" v-else>
            <i class="el-icon-video-camera"></i>
            <p>上传视频后可在此预览</p>
          </div>

          <!-- 历史上传列表 -->
          <div class="history-list">
            <h4>历史上传</h4>
            <el-table
              :data="historyList"
              border
              size="small"
              style="width: 100%; margin-top: 10px"
            >
              <el-table-column prop="name" label="文件名" width="200"></el-table-column>
              <el-table-column prop="size" label="大小" width="100">
                <template #default="scope">{{ formatSize(scope.row.size) }}</template>
              </el-table-column>
              <el-table-column prop="duration" label="时长" width="100"></el-table-column>
              <el-table-column prop="uploadTime" label="上传时间"></el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="previewHistoryVideo(scope.row.url)"
                  >
                    预览
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      // 上传配置
      uploadUrl: '/api/video/upload', // 后端上传接口
      fileList: [], // 待上传文件列表
      uploading: false, // 是否正在上传
      uploadProgress: 0, // 上传进度（百分比）

      // 状态提示
      showStatusAlert: false,
      statusMessage: '',
      statusType: '', // success/warning/error

      // 预览相关
      previewVideoUrl: '', // 当前预览视频URL
      currentVideoName: '',
      currentVideoSize: 0,
      currentVideoDuration: '',
      videoPoster: '', // 视频封面（第一帧）

      // 历史上传记录（模拟数据，实际从后端获取）
      historyList: [
        {
          name: 'sample-video.mp4',
          size: 25600000, // 25.6MB
          duration: '02:30',
          url: '/videos/sample.mp4',
          uploadTime: '2024-05-20 14:30:25'
        }
      ]
    };
  },
  methods: {
    // 上传前验证
    handleBeforeUpload(file) {
      // 格式验证
      const allowedTypes = ['video/mp4', 'video/avi', 'video/mov', 'video/flv'];
      const isAllowedType = allowedTypes.includes(file.type);
      if (!isAllowedType) {
        this.showAlert('请上传 MP4、AVI、MOV 或 FLV 格式的视频', 'error');
        return false;
      }

      // 大小验证（200MB）
      const maxSize = 200 * 1024 * 1024; // 200MB
      const isLt200M = file.size <= maxSize;
      if (!isLt200M) {
        this.showAlert('视频大小不能超过 200MB', 'error');
        return false;
      }

      // 读取视频信息（时长、封面）
      this.getVideoInfo(file);

      return true;
    },

    // 获取视频信息（时长、封面）
    getVideoInfo(file) {
      const video = document.createElement('video');
      video.preload = 'metadata';
      video.onloadedmetadata = () => {
        // 清除内存
        URL.revokeObjectURL(video.src);

        // 时长格式化（秒 → MM:SS）
        const duration = video.duration;
        const minutes = Math.floor(duration / 60);
        const seconds = Math.floor(duration % 60);
        this.currentVideoDuration = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

        // 截取第一帧作为封面
        this.captureVideoFrame(video, file);
      };
      video.src = URL.createObjectURL(file);
    },

    // 截取视频第一帧作为封面
    captureVideoFrame(video, file) {
      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
      this.videoPoster = canvas.toDataURL('image/jpeg');

      // 保存当前视频信息
      this.currentVideoName = file.name;
      this.currentVideoSize = file.size;
    },

    // 开始上传
    submitUpload() {
      if (this.fileList.length === 0) return;

      this.uploading = true;
      this.uploadProgress = 0;

      // 手动构建 FormData 并上传（如需自定义请求头或额外参数）
      const formData = new FormData();
      formData.append('videoFile', this.fileList[0].raw);
      formData.append('fileName', this.fileList[0].name); // 可选：额外参数

      axios.post(this.uploadUrl, formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
        onUploadProgress: (progressEvent) => {
          // 计算上传进度
          const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
          this.uploadProgress = percent;
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.showAlert('视频上传成功', 'success');
          // 上传成功后设置预览URL（实际应使用后端返回的URL）
          this.previewVideoUrl = URL.createObjectURL(this.fileList[0].raw);
          // 添加到历史记录
          this.historyList.unshift({
            name: this.currentVideoName,
            size: this.currentVideoSize,
            duration: this.currentVideoDuration,
            url: res.data.data.videoUrl, // 后端返回的视频URL
            uploadTime: new Date().toLocaleString()
          });
        } else {
          this.showAlert(`上传失败：${res.data.msg}`, 'error');
        }
      }).catch(err => {
        this.showAlert(`上传失败：${err.message}`, 'error');
      }).finally(() => {
        this.uploading = false;
        this.fileList = []; // 清空文件列表
      });
    },

    // 清空文件
    clearFiles() {
      this.fileList = [];
      this.previewVideoUrl = '';
      this.currentVideoName = '';
      this.currentVideoSize = 0;
      this.currentVideoDuration = '';
    },

    // 上传进度回调（Element UI 自带）
    handleProgress(event, file, fileList) {
      this.uploadProgress = Math.round(event.percent);
    },

    // 上传成功回调（Element UI 自带，若使用 action 自动上传）
    handleSuccess(response, file, fileList) {
      // 若使用 Element UI 自带的 action 上传，在此处理成功逻辑
    },

    // 上传失败回调
    handleError(err, file, fileList) {
      this.showAlert('上传失败，请重试', 'error');
      this.uploading = false;
    },

    // 预览历史视频
    previewHistoryVideo(url) {
      this.previewVideoUrl = url;
      // 实际项目中可通过 URL 请求视频信息更新 currentVideoXXX
    },

    // 格式化文件大小（字节 → MB/KB）
    formatSize(bytes) {
      if (bytes < 1024) return `${bytes} B`;
      if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
      return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
    },

    // 显示状态提示
    showAlert(message, type) {
      this.statusMessage = message;
      this.statusType = type;
      this.showStatusAlert = true;
    }
  }
};
</script>

<style scoped>
.video-upload-page {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

.layout-container {
  display: flex;
  gap: 20px;
  height: calc(100vh - 120px);
}

/* 左侧上传区域 */
.upload-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.upload-tip {
  color: #666;
  font-size: 12px;
  margin-top: 10px;
  line-height: 1.5;
}

.upload-controls {
  margin-top: 20px;
}

.btn-group {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

/* 右侧预览区域 */
.preview-container {
  flex: 1.5;
  display: flex;
  flex-direction: column;
}

.preview-box {
  margin-top: 10px;
}

.preview-video {
  width: 100%;
  max-height: 400px;
  object-fit: contain;
  border-radius: 4px;
  background-color: #000;
}

.video-info {
  margin-top: 15px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.video-info p {
  margin: 5px 0;
  color: #333;
}

.empty-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #999;
  border: 1px dashed #ddd;
  border-radius: 4px;
  margin-top: 10px;
}

.empty-preview i {
  font-size: 48px;
  margin-bottom: 15px;
}

.history-list {
  margin-top: 30px;
}

.history-list h4 {
  color: #666;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: 500;
}
</style>
